<template>
  <el-dialog v-model="dialogVisible" title="修改密码" width="500px" draggable>
    <el-form ref="ruleFormRef" label-width="100px" label-suffix=":" :rules="rules" :model="operateDataInfo">
      <el-form-item label="旧密码" prop="oldPassword">
        <el-input
          v-model="operateDataInfo.oldPassword"
          type="password"
          show-password
          placeholder="请输入旧密码"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input
          v-model="operateDataInfo.newPassword"
          type="password"
          show-password
          placeholder="请输入新密码"
          clearable
        ></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import { changePassword, SysUserChangePasswordParam } from "@/api/modules/sys/user";

const dialogVisible = ref(false);
const openDialog = () => {
  operateDataInfo.value = { oldPassword: "", newPassword: "" };
  dialogVisible.value = true;
};

const rules = reactive({
  oldPassword: [{ required: true, message: "请输入旧密码" }],
  newPassword: [{ required: true, message: "请输入新密码" }]
});

const operateDataInfo = ref<SysUserChangePasswordParam>({ oldPassword: "", newPassword: "" });

const ruleFormRef = ref<FormInstance>();
const handleSubmit = () => {
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    try {
      await changePassword(operateDataInfo.value);
      ElMessage.success({ message: `密码修改 成功！` });
      dialogVisible.value = false;
    } catch (error) {
      console.log(error);
    }
  });
};

defineExpose({ openDialog });
</script>
